--- --- hook  掉 inst.AnimState  不依赖mod加载优先级，方便和其他MOD兼容


modimport("Original_AnimState_Upgrade_for_npc/Special_hook_TheSim.lua")    --- 更新 PlayAnimation 和 PushAnimation 



TUNING.NPC_UPGRADE_ANIMSTATE_FN = {}
if TUNING.NPC_MOD_TEST_DEBUG == true then
    -- modimport("Original_AnimState_Upgrade_for_npc/00_PlayAnim_PushAnim.lua")    --- 更新 PlayAnimation 和 PushAnimation 
    -- modimport("Original_AnimState_Upgrade_for_npc/01_GetBuild.lua")    --- 更新 PlayAnimation 和 PushAnimation 
end

local function theAnimState_fn_Upgrade(theAnimState)
    for fn_name, fn in pairs(TUNING.NPC_UPGRADE_ANIMSTATE_FN) do
        if fn and type(fn) == "function" then
            fn(theAnimState)
        end
    end
end


local function Hook_Player_AnimState(inst)

    if type(inst.AnimState) == "userdata" then            ----- 只能转变一次，重复的操作 会导致  __index 函数错误
        --------------------------------------------------------------------------------------------------------------------------------
            inst.__AnimState_userdata_npc = inst.AnimState      ----- 转移复制原有 userdata
            inst.AnimState = {inst = inst , name = "AnimState"}   ----- name 是必须的，用于 从 _G  里 得到目标, 玩家 inst 也是从这里进入
            ------ 逻辑上复现棱镜模组的代码：

            setmetatable( inst.AnimState , {
                __index = function(_table,fn_name)
                            if _table and _table.inst and _table.name then

                                    if _G[_table.name][fn_name] then    ---- 从_G全局里得到原函数？？这句并不好理解。   ---- lua 会往_G 里自动挂载所有要运行的 userdata ？？
                                        local _table_name = _table.name
                                        local fn = function(temp_table,...)
                                            return _G[_table_name][fn_name](temp_table.inst.__AnimState_userdata_npc,...)
                                        end
                                        rawset(_table,fn_name,fn)
                                        return fn
                                    end

                            end
                end,
            })
        --------------------------------------------------------------------------------------------------------------------------------
    end

    ------- 成功把  inst.AnimState 从  userdata 变成 table
    --------------------- 挂载函数
    if inst.AnimState.inst ~= inst then
        inst.AnimState.inst = inst
    end
    ---------------------
    theAnimState_fn_Upgrade(inst.AnimState)

end

AddPlayerPostInit(function(inst)
    if not TheWorld.ismastersim then
		return
	end

    inst:DoTaskInTime(0,function()  --- 玩家完全进入游戏后。再侵入。不然遭遇棱镜会冲突失效        
        Hook_Player_AnimState(inst)
    end)
end)